using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class DuctTaper : MonoBehaviour {
	
	public int tapeAmount = 3;
	public int placementTries = 20;
	
	public GameObject tapePrefab;
	
	public float tapeDistance = 20f;
	
	public Transform testTarget;
	public Transform testParent;
	
	public bool drawGizmoid = false;
	
	private List<List<Vector3>> hitListList = new List<List<Vector3>>();

	// Use this for initialization
	void Start () {	
		if(testTarget != null && testParent != null){
			tapeItem(testTarget,testParent);
		}
	}
	
	public void tapeItem(Transform target,Transform tapeParent){
		//Create the set amount of tape pieces
		for(int i = 0;i<tapeAmount;i++){
			//create a tape piece;
			GameObject tapePiece = Instantiate(tapePrefab,Vector3.zero,Quaternion.identity) as GameObject;
			//Try to tape them
			for(int j = 0;j<placementTries;j++){
				//randomise a positon around the target point and rotate towards point.
				//tapePiece.transform.position = target.transform.position+(target.transform.forward);
				Quaternion rot = Quaternion.Euler(new Vector3(Random.Range(0,360),Random.Range(0,360),0));
				Vector3 pos = rot * new Vector3(0,0,tapeDistance)+target.position;
				tapePiece.transform.rotation = rot;
				tapePiece.transform.position = pos;
				
//				tapePiece.transform.localRotation = Quaternion.LookRotation(tapePiece.transform.position-target.position);
//				tapePiece.transform.localRotation = tapePiece.transform.localRotation*Quaternion.Euler(new Vector3(90,0,0));
					
				
				//Try to place piece and if we managed to place it move to next piece
				if(slickTape(target,tapePiece)){
					tapePiece.transform.parent = tapeParent;
					break;
				}else{
					Destroy(tapePiece);
					Debug.Log("something is wrong");
				}
			}
		}
	}
//	
	bool slickTape(Transform target,GameObject tapeObject){
		if(tapeObject.GetComponent<DuctTape>().tape(target))
			return true;
		else
			return false;
	}
	void OnDrawGizmos(){
		if(drawGizmoid){
			Gizmos.color = Color.blue;
			foreach(List<Vector3> l in hitListList){
				foreach(Vector3 v in l){
					Gizmos.DrawSphere(v,0.005f);
				}
			}
		}
	}
}
